package com.xjrsoft.third;

import com.xjrsoft.third.entity.HttpSendConstant;
import com.xjrsoft.third.entity.HttpSendParams;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

@Slf4j
public class HttpClientUtils {


    /**
     * 请求第三方接口
     * @param params 请求参数
     * @return
     */
    public static Response send(HttpSendParams params){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse(params.getContentType());
        RequestBody body = null;
        if(HttpSendConstant.POST.equals(params.getMethod())){
            body = RequestBody.create(mediaType, "");
        }
        Request request = new Request.Builder()
                .url(params.getUrl())
                .method(params.getMethod(), body)
                .addHeader("Content-Type", params.getContentType())
                .addHeader("Authorization", params.getAuthorization())
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            log.error("HttpClientUtils ERROR: url [{}]",params.getUrl(),e);
        }
        return null;
    }

}
